package post.ui;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import post.Client;
import post.Payment;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Ayush, David
 */
public class guiOfPost extends javax.swing.JFrame {

    /**
     * Creates new form guiOfPost
     */
    
    /*This variable enterCount is used to keep track of no of items entered (How many times ENTER is hit)*/
    int enterCount = 0;         //can also be interpreted as row number.
    Client client;
    float totalAmount = 0;
    
    
    public guiOfPost() throws IOException, RemoteException, NotBoundException {
        initComponents();
        //ProductCatalog pc = new ProductCatalog();
        //System.out.println(pc.getAllProductsUpc());        
       currentSystemTime.setText(new Date().toString());    //Set system time on the frame 
        
            client = new Client();
            client.init();
            System.out.println(client.getAllUPC());
            
            /*for each loop populating the upcComboBox*/
            for(String upcs : client.getAllUPC())
            {
                upc.addItem(upcs);
            }
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        productPanel = new javax.swing.JPanel();
        upcLabel = new javax.swing.JLabel();
        quantityLabel = new javax.swing.JLabel();
        enter = new javax.swing.JButton();
        quantity = new javax.swing.JComboBox();
        upc = new javax.swing.JComboBox();
        customerNameLabel = new javax.swing.JLabel();
        customerName = new javax.swing.JTextField();
        invoicePanel = new javax.swing.JPanel();
        scrollPane = new javax.swing.JScrollPane();
        productsTable = new javax.swing.JTable();
        paymentPanel = new javax.swing.JPanel();
        paymentTypeCombobox = new javax.swing.JComboBox();
        paymentType = new javax.swing.JLabel();
        amountLabel = new javax.swing.JLabel();
        amount = new javax.swing.JTextField();
        payButton = new javax.swing.JButton();
        currentSystemTime = new javax.swing.JLabel();
        grandTotalLabel = new javax.swing.JLabel();
        grandTotal = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("POST Terminal");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocationByPlatform(true);
        setResizable(false);
        addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                formComponentAdded(evt);
            }
        });

        productPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Product"));
        productPanel.setToolTipText("");

        upcLabel.setText("UPC");

        quantityLabel.setText("Quantity");

        enter.setText("ENTER");
        enter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                enterMouseClicked(evt);
            }
        });

        quantity.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }));

        javax.swing.GroupLayout productPanelLayout = new javax.swing.GroupLayout(productPanel);
        productPanel.setLayout(productPanelLayout);
        productPanelLayout.setHorizontalGroup(
            productPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(productPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(productPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(productPanelLayout.createSequentialGroup()
                        .addComponent(upcLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(upc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(quantityLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(quantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, productPanelLayout.createSequentialGroup()
                        .addComponent(enter)
                        .addGap(87, 87, 87))))
        );
        productPanelLayout.setVerticalGroup(
            productPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(productPanelLayout.createSequentialGroup()
                .addGroup(productPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(upcLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quantityLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(upc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(enter)
                .addContainerGap())
        );

        customerNameLabel.setText("Customer Name");

        invoicePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Invoice"));
        invoicePanel.setName(""); // NOI18N

        productsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null}
            },
            new String [] {
                "Item Description", "Quantity", "Unit Price", "Total Per Item"
            }
        ));
        scrollPane.setViewportView(productsTable);

        paymentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Payment"));
        paymentPanel.setName("Payment"); // NOI18N

        paymentTypeCombobox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cash", "Credit Card", "Cheque" }));
        
        paymentTypeCombobox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                paymentTypeComboboxChanged(e);
            }
        });
        
        payButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
               payButtonMouseClicked(evt);
            }
        });

        paymentType.setText("Payment type");

        amountLabel.setText("Amount");

        payButton.setText("Pay");

        javax.swing.GroupLayout paymentPanelLayout = new javax.swing.GroupLayout(paymentPanel);
        paymentPanel.setLayout(paymentPanelLayout);
        paymentPanelLayout.setHorizontalGroup(
            paymentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(paymentPanelLayout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(paymentType)
                .addGap(18, 18, 18)
                .addComponent(paymentTypeCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addComponent(amountLabel)
                .addGap(18, 18, 18)
                .addComponent(amount, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(paymentPanelLayout.createSequentialGroup()
                .addGap(195, 195, 195)
                .addComponent(payButton))
        );
        paymentPanelLayout.setVerticalGroup(
            paymentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(paymentPanelLayout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addGroup(paymentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(paymentTypeCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(paymentType)
                    .addComponent(amountLabel)
                    .addComponent(amount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(payButton))
        );

        currentSystemTime.setText("currentSystemTime");

        grandTotalLabel.setText("Grand Total");

        javax.swing.GroupLayout invoicePanelLayout = new javax.swing.GroupLayout(invoicePanel);
        invoicePanel.setLayout(invoicePanelLayout);
        invoicePanelLayout.setHorizontalGroup(
            invoicePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(invoicePanelLayout.createSequentialGroup()
                .addGroup(invoicePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(invoicePanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(scrollPane))
                    .addGroup(invoicePanelLayout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(currentSystemTime, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(paymentPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, invoicePanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(grandTotalLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(53, 53, 53)
                        .addComponent(grandTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        invoicePanelLayout.setVerticalGroup(
            invoicePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(invoicePanelLayout.createSequentialGroup()
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(invoicePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(invoicePanelLayout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addComponent(currentSystemTime, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, invoicePanelLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(invoicePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(grandTotalLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(grandTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(paymentPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(invoicePanel, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(customerNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(customerName, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(91, 91, 91)
                        .addComponent(productPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(38, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(productPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(customerNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(customerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(invoicePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        invoicePanel.getAccessibleContext().setAccessibleName("invoice");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void enterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_enterMouseClicked
          
/*Addition of items to the table. Event is triggered when the user hits 'ENTER'*/
            String selectedUpc = (String)upc.getSelectedItem();
            String desc = client.getDescByUPC(selectedUpc);
            float price = client.getPriceByUPC(selectedUpc);
            int qty = Integer.parseInt((String)quantity.getSelectedItem());
            client.addItemToCart(selectedUpc, qty);
            productsTable.setValueAt(desc, enterCount, 0);
            productsTable.setValueAt(qty, enterCount, 1);
            productsTable.setValueAt(price, enterCount, 2);
            productsTable.setValueAt(qty*price, enterCount, 3);
            enterCount++;
            totalAmount = client.getTotal();
            //totalAmount = totalAmount + qty*price;
            DefaultTableModel model = (DefaultTableModel) productsTable.getModel(); 
            model.addRow(new Object [][] {null, null, null, null});                 //Adds blank row to the table for adding more products.
            grandTotal.setText(String.valueOf(totalAmount));



       
}//GEN-LAST:event_enterMouseClicked

    private void formComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_formComponentAdded
        // TODO add your handling code here:
    }//GEN-LAST:event_formComponentAdded


    private void payButtonMouseClicked(java.awt.event.MouseEvent evt) {

       try{
           if(paymentTypeCombobox.getSelectedItem().toString().equals("Cash")){
               float amountPayedFloat = Float.parseFloat(amount.getText());
               client.checkOut(customerName.getText(), Payment.Cash, amountPayedFloat, 0);
           }else  if(paymentTypeCombobox.getSelectedItem().toString().equals("Credit Card")){
               int cardNum = Integer.parseInt(amount.getText());
               client.checkOut(customerName.getText(), Payment.CreditCard, 0.F, cardNum);
           }else  if(paymentTypeCombobox.getSelectedItem().toString().equals("Cheque")){
               int chequeNum = Integer.parseInt(amount.getText());
               client.checkOut(customerName.getText(), Payment.Cheque, 0.F, chequeNum);
           }
           reset();
        }catch (Exception e){System.out.println("Error, empty text field");}
        
    }
    
    private void paymentTypeComboboxChanged(ActionEvent e) {
        String choice = paymentTypeCombobox.getSelectedItem().toString();
        if(choice.equals("Cash")) {
            amountLabel.setText("Amount");
        } else if (choice.equals("Credit Card")) {
            amountLabel.setText("Card #");
        } else if (choice.equals("Cheque")) {
            amountLabel.setText("Cheque #");
        }
    }
    
    private void reset() {
        DefaultTableModel model = (DefaultTableModel) productsTable.getModel();
        for(int i = enterCount-1; i >= 0; i--) {
            model.removeRow(i);
            enterCount--;
        }
        amount.setText("");
        customerName.setText("");
        grandTotal.setText(String.valueOf(client.getTotal()));
        paymentTypeCombobox.setSelectedIndex(0);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]){
     
     
        
        
        
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(guiOfPost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(guiOfPost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(guiOfPost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(guiOfPost.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                
                    try {
                        new guiOfPost().setVisible(true);
                    } catch (IOException ex) {
                        Logger.getLogger(guiOfPost.class.getName()).log(Level.SEVERE, null, ex);
                    } 
                     catch (NotBoundException ex) {
                        Logger.getLogger(guiOfPost.class.getName()).log(Level.SEVERE, null, ex);
                    }
                 
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField amount;
    private javax.swing.JLabel amountLabel;
    private javax.swing.JLabel currentSystemTime;
    private javax.swing.JTextField customerName;
    private javax.swing.JLabel customerNameLabel;
    private javax.swing.JButton enter;
    private javax.swing.JLabel grandTotal;
    private javax.swing.JLabel grandTotalLabel;
    private javax.swing.JPanel invoicePanel;
    private javax.swing.JButton payButton;
    private javax.swing.JPanel paymentPanel;
    private javax.swing.JLabel paymentType;
    private javax.swing.JComboBox paymentTypeCombobox;
    private javax.swing.JPanel productPanel;
    private javax.swing.JTable productsTable;
    private javax.swing.JComboBox quantity;
    private javax.swing.JLabel quantityLabel;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JComboBox upc;
    private javax.swing.JLabel upcLabel;
    // End of variables declaration//GEN-END:variables


}